package flc.ast.activity;

import android.net.Uri;
import android.os.Handler;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelDocAdapter;
import flc.ast.bean.MyDocBean;
import flc.ast.databinding.ActivityDocManageBinding;
import flc.ast.utils.OpenFileUtil;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class DocManageActivity extends BaseAc<ActivityDocManageBinding> {

    private List<MyDocBean> listShow = new ArrayList<>();
    private List<MyDocBean> listDelete = new ArrayList<>();
    private SelDocAdapter docAdapter;
    private boolean isEdit = false;
    private boolean isSelectAll = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_doc_manage;
    }

    @Override
    public void onBackPressed() {
        if (isEdit) {
            isEdit = false;
            listDelete.clear();
            docAdapter.setEdit(isEdit);
            getData();
            mDataBinding.ivDocManageEdit.setVisibility(View.VISIBLE);
            mDataBinding.llDocManageBottom.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivDocManageBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.rvDocList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        docAdapter = new SelDocAdapter();
        docAdapter.setEdit(isEdit);
        mDataBinding.rvDocList.setAdapter(docAdapter);
        docAdapter.setOnItemClickListener(this);

        mDataBinding.ivDocManageEdit.setOnClickListener(this);
        mDataBinding.llSelectAll.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDocManageEdit://管理
                isEdit = true;
                docAdapter.setEdit(isEdit);
                docAdapter.notifyDataSetChanged();
                mDataBinding.ivDocManageEdit.setVisibility(View.GONE);
                mDataBinding.llDocManageBottom.setVisibility(View.VISIBLE);
                break;
            case R.id.llSelectAll://全选
                listDelete.clear();
                if (isSelectAll) {
                    for (MyDocBean validDatum : docAdapter.getValidData()) {
                        validDatum.setSelect(false);
                    }
                } else {
                    for (MyDocBean validDatum : docAdapter.getValidData()) {
                        validDatum.setSelect(true);
                        listDelete.add(validDatum);
                    }
                }
                isSelectAll();
                docAdapter.notifyDataSetChanged();
                break;
            case R.id.tvDelete://删除
                if (listDelete.size() == 0) {
                    return;
                }
                delete();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (docAdapter.getItem(position).isSelect()) {
                docAdapter.getItem(position).setSelect(false);
                listDelete.remove(docAdapter.getItem(position));
                docAdapter.notifyDataSetChanged();
            } else {
                listDelete.add(docAdapter.getItem(position));
                docAdapter.getItem(position).setSelect(true);
                docAdapter.notifyDataSetChanged();
            }
            isSelectAll();
        } else {
            OpenFileUtil.getInstance().openFile(mContext, FileUtils.getFileByPath(docAdapter.getItem(position).getPath()));
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_all_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }
                })
                .request();
    }

    //获取文档数据
    private void getData() {
        //设置获取的数据类型 只获取pdf
        List<String> type = new ArrayList<>();
        type.add("application/msword");
        type.add("application/vnd.ms-excel");
        type.add("application/vnd.ms-powerpoint");
        type.add("application/pdf");
        type.add("text/plain");
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<MediaInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MediaInfo>> emitter) {
                List<MediaInfo> infoList = MediaLoader.loadDoc(type);
                emitter.onNext(infoList);
            }

            @Override
            public void accept(List<MediaInfo> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    for (MediaInfo bean : selectMediaEntities) {
                        listShow.add(new MyDocBean(bean.getName(), bean.getPath(), bean.getUri()
                                , ConvertUtils.byte2FitMemorySize(bean.getSize(), 3)
                                , TimeUtils.millis2String(FileUtils.getFileLastModified(bean.getPath()), "yyyy/MM/dd"), false));
                    }
                }
                if (listShow.size() > 0) {
                    docAdapter.setList(listShow);
                    mDataBinding.rvDocList.setVisibility(View.VISIBLE);
                    mDataBinding.ivDocManageNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvDocList.setVisibility(View.GONE);
                    mDataBinding.ivDocManageNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void isSelectAll() {
        if (listDelete.size() == docAdapter.getValidData().size()) {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.aquanxuan);
            isSelectAll = true;
        } else {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.aweiquanx);
            isSelectAll = false;
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        for (int i = 0; i < listDelete.size(); i++) {
                            //从此文件夹删除
                            mContext.getContentResolver().delete(Uri.parse(listDelete.get(i).getUri()), null, null);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        listDelete.clear();
                        isEdit = false;
                        docAdapter.setEdit(isEdit);
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        mDataBinding.llDocManageBottom.setVisibility(View.GONE);
                    }
                });
            }
        }, 1000);
    }

}